package com.yz;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yz.constant.R;
import com.yz.constenum.Currency;
import com.yz.utils.EmptyUtil;
import com.yz.utils.Md5Util;
import com.yz.utils.RSAUtil;
import com.yz.utils.RequestUtils;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

@RestController
public class PayOrderController {

    public static final org.slf4j.Logger logger = LoggerFactory.getLogger(PayOrderController.class);
    /****
     * 商户号
     */
    public final static String merchNo = "CPSH139727";
    /**
     * 公钥 --聚富
     */
    public final static String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDA0fr7Ln/PJCAl4YnnmxZgSloxlB4cFNd+qRIShT9yIZ6laDYwxt9e5mQ/S4ZQF1s8n5c37jcYX8+0OrZRq65ccDHeJ7RBcOajKq9KuzHvICt5fLmeJqK/hZ4gQcLqp+QPrkxHCiQd/zUOOx43kMy4MMbvyMeJvVwEmfQwpey1bQIDAQAB";
    /**
     * 公钥 --商户
     */
    public final static String mcPublicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDhkhhq7yH7JwHp8jebrRdJiqXuKdZc8YCuOoyHD1cu6FOvNTY2KpOQ/o+3BreKzjwfPcQqlFfosVHkS3l7jwv9CsQRUxxZEjP/ZhBwl63TOUEpv+v1Apfrpll81wHfL2uSDB3C+lwSQqKOPuWy/jHPhpZ84qezyGfIPXK/ysJd3wIDAQAB";
    /**
     * 私钥---商户
     */
    public final static String mcPrivateKey = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBALG75NrKjqz20vHuKP05e5ov3Of2MEXcda1oPD7HYdeok32S6Zra8UiUFRyol/FeeZ9z0cwl5DjvLoj/U+t8RutoVqEZCbdXP0JmIV28RN4b5NGnnNvp+akKjwwvcqad7OaPvI+GupMg1KVzvksdzU9K8uEu0h30kf4ZvHw6gADJAgMBAAECgYAJhkAlWWV7714uiMy5hTMSeC4mYBMGK2JDAKr50kV0ARymRhEuszzq3sSi3IYH8UAjQ1mizwUD6A1eWhBtNiO2so3Goms/GbPW1txbz+2H6a+Xrw+h79e5nDSyKBSM7qNwo1nHgy2koBFBBAV6az+wVnBYo3fKNfU9YlTm6pRY4QJBAP8w41FEhrfoli+2hd77hQ+RNMukXSztRPN8NMqURFka/62apkR4hUV/5L1aboVvrejbaDriTQpfWt6VEil7mgsCQQCyTCRmP4oQ1ld1vzRFkkCc+3VNu8aA3QzqS4aScrhXdBGKfBb3PWc+nrupq7O43j5in/7MQHWGhTNMe0vH4uj7AkEAyOAuz9XlRfcr4bsHfhL3Ft3ydSqYvbi3wgJPe/diJdH+2SUXJGbKYX7fC76XqSnT96xeS5u/kR6mZPdrKIRHKQJAC+AQaJMA0iBEkP4cMCoOjaYd6QCBtyGB87T2EJj9eC2t4WhkazE2yC/wVduuy7hZtV3srZP5f+0tPoHTyUtuswJBAIwO75Rzbz/wa1fp7jAtycGcjR57GwHF9OHKZm66TfD1WRDg3kTWb+k3MvmCJmHc/3ehZYajl2UQAqt/r9SAoPU=";
    /***
     * 支付域名
     */
    public final static String url = "http://localhost:9999/pay/order";

    /****
     * 绑卡域名
     */
    public final static String card_url = "http://localhost:9999/pay/card";

    /**
     *
     *订单支付测试
     * @throws Exception
     */
    @RequestMapping("/pay/order")
    public R payOrder(@RequestParam("publicKey") String publicKey, @RequestParam("mcPrivateKey") String mcPrivateKey,
                      JSONObject jsObj) throws Exception {
        if(EmptyUtil.isEmpty(publicKey)){
            publicKey = PayOrderController.publicKey;
        }
        if(EmptyUtil.isEmpty(mcPrivateKey)){
            mcPrivateKey = PayOrderController.mcPrivateKey;
        }
        String reqTime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        //商户号
        jsObj.put("merchNo", merchNo);
        //订单号
        jsObj.put("orderNo", reqTime + new Random().nextInt(10000));
        //用户标志
        jsObj.put("userId", "11111");
        //订单标题
        //jsObj.put("title", "充值");
        //支付金额 单位 元  其他币种为个数
        jsObj.put("amount", "100");
        //币种
        jsObj.put("currency", Currency.USDT.name());
        //前端返回地址
        jsObj.put("returnUrl", "http://www.baidu.com");
        //后台通知地址
        jsObj.put("notifyUrl", "http://www.baidu.com");

        //encryptType 签名方式  MD5 RSA  默认为 RSA
        //jsObj.put("encryptType", "RSA");
        //请求时间
        //jsObj.put("reqTime", reqTime);
        byte[] context = RSAUtil.encryptByPublicKey(JSON.toJSONBytes(jsObj), publicKey);
        String sign = RSAUtil.sign(context, mcPrivateKey);
        logger.info("签名结果：{}" ,sign);
        JSONObject jo = new JSONObject();
        jo.put("sign", sign);
        jo.put("context", context);
        logger.info("请求参数：{}", jo.toJSONString());
        String result = RequestUtils.doPostJson(url, jo.toJSONString());
        logger.info("请求结果！{}",result);
        jo = JSONObject.parseObject(result);
        if("0".equals(jo.getString("code"))){
            sign = jo.getString("sign");
            context = jo.getBytes("context");
            if(RSAUtil.verify(context, publicKey, sign)){
                String source = new String(RSAUtil.decryptByPrivateKey(context, mcPrivateKey));
                logger.info("解密结果：" + source);
                jo = JSONObject.parseObject(source);
                logger.info("支付链接地址：{}", jo.getString("code_url"));
            }else{
                logger.info("验签失败！{}");
            }
        }
        return R.okData(jo);
    }


    /**
     *
     *订单支付测试
     * @throws Exception
     */
    public void order_test_md5() throws Exception{
        JSONObject jsObj = new JSONObject();
        String reqTime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        //商户号
        jsObj.put("merchNo", merchNo);
        //订单号
        jsObj.put("orderNo", reqTime + new Random().nextInt(10000));
        //用户标志
        //jsObj.put("userId", "userId");
        //订单标题
        //jsObj.put("title", "充值");
        //支付金额 单位 元  其他币种为个数
        jsObj.put("amount", "100");
        //币种
        jsObj.put("currency", Currency.CNY.name());
        //前端返回地址
        jsObj.put("returnUrl", "http://www.baidu.com");
        //后台通知地址
        jsObj.put("notifyUrl", "http://www.baidu.com");


        byte[] context = JSON.toJSONBytes(jsObj);
        String sign = Md5Util.sign(new String(context,"UTF-8"),mcPrivateKey,"UTF-8");
        logger.info("签名结果：{}" ,sign);
        JSONObject jo = new JSONObject();
        jo.put("sign", sign);
        jo.put("context", context);
        //encryptType 签名方式  MD5 RSA  默认为 RSA
        jo.put("encryptType", "MD5");
        logger.info("请求参数：{}", jo.toJSONString());
        String result = RequestUtils.doPostJson(url, jo.toJSONString());
        logger.info("请求结果！{}",result);
        jo = JSONObject.parseObject(result);
        if("0".equals(jo.getString("code"))){
            sign = jo.getString("sign");
            context = jo.getBytes("context");
            if(Md5Util.verify(new String(context,"UTF-8"), sign,mcPrivateKey,"UTF-8")){
                String source = new String(context,"UTF-8");
                logger.info("解密结果：" + source);
                jo = JSONObject.parseObject(source);
                logger.info("支付链接地址：{}", jo.getString("code_url"));
            }else{
                logger.info("验签失败！{}");
            }
        }
    }


    /**
     *
     * @Description 支付订单查询
     * @throws Exception
     */
    public void order_query() throws Exception{
        String orderNo = "201809251938577854";
        JSONObject jsObj = new JSONObject();
        //商户号
        jsObj.put("merchNo", merchNo);
        jsObj.put("orderNo", orderNo);
        byte[] context = RSAUtil.encryptByPublicKey(JSON.toJSONBytes(jsObj), publicKey);
        String sign = RSAUtil.sign(context, mcPrivateKey);
        logger.info("签名结果：{}" ,sign);
        JSONObject jo = new JSONObject();
        jo.put("sign", sign);
        jo.put("context", context);
        logger.info("请求参数：{}", jo.toJSONString());
        String result = RequestUtils.doPostJson(url + "/query", jo.toJSONString());
        logger.info("请求结果！{}",result);
        jo = JSONObject.parseObject(result);
        if("0".equals(jo.getString("code"))){
            sign = jo.getString("sign");
            context = jo.getBytes("context");
            if(RSAUtil.verify(context, publicKey, sign)){
                String source = new String(RSAUtil.decryptByPrivateKey(context, mcPrivateKey));
                logger.info("解密结果：" + source);
                jo = JSONObject.parseObject(source);
                logger.info("订单支付状态", jo.getString("orderState"));

            }else{
                logger.info("验签失败！{}");
            }
        }
    }


    /**
     *
     * @Description 代付订单
     * @throws Exception
     */
    public void order_acp() throws Exception{
        JSONObject jsObj = new JSONObject();
        String reqTime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        //商户号
        jsObj.put("merchNo", merchNo);
        //订单号
        jsObj.put("orderNo", reqTime + new Random().nextInt(10000));
        jsObj.put("bankCode", "BOC");
        jsObj.put("bankBranch", "建设银行长沙支行");
        jsObj.put("acctName","chdx");
        jsObj.put("bankNo","64646464646464664");
        jsObj.put("walletAddr","walletAddr.......");
        //jsObj.put("certNo","8888");
        //订单标题
        //jsObj.put("title", "商城网银代付");
        //产品名称
        //jsObj.put("product", "产品名称");
        //代付付金额 单位 元
        jsObj.put("amount", "100");
        //币种
        jsObj.put("currency", Currency.USDT.name());
        //后台通知地址
        jsObj.put("notifyUrl", "http://www.baidu.com");
        //请求时间
        jsObj.put("reqTime", reqTime);

        byte[] context = RSAUtil.encryptByPublicKey(JSON.toJSONBytes(jsObj), publicKey);
        String sign = RSAUtil.sign(context, mcPrivateKey);
        logger.info("签名结果：{}" ,sign);
        JSONObject jo = new JSONObject();
        jo.put("sign", sign);
        jo.put("context", context);
        logger.info("请求参数：{}", jo.toJSONString());
        String result = RequestUtils.doPostJson(url + "/acp", jo.toJSONString());
        logger.info("请求结果！{}",result);
        jo = JSONObject.parseObject(result);
        if("0".equals(jo.getString("code"))){
            sign = jo.getString("sign");
            context = jo.getBytes("context");
            if(RSAUtil.verify(context, publicKey, sign)){
                String source = new String(RSAUtil.decryptByPrivateKey(context, mcPrivateKey));
                logger.info("解密结果：" + source);
                jo = JSONObject.parseObject(source);
                logger.info("代付消息：{}", jo.getString("msg"));
            }else{
                logger.info("验签失败！{}");
            }
        }
    }
}
